package com.jci.vsd.activity.enterprise;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.activity.LoginActivity;
import com.jci.vsd.activity.Reim.ReimRecycActivity;
import com.jci.vsd.bean.enterprise.MembersBean;
import com.jci.vsd.bean.enterprise.ProducerBean;
import com.jci.vsd.bean.enterprise.ProducerSettingInfoBean;
import com.jci.vsd.bean.enterprise.ProducerUpdateBean;
import com.jci.vsd.constant.AppConstant;
import com.jci.vsd.data.ReimAddData;
import com.jci.vsd.network.control.ProducerManageControl;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.view.widget.SimpleToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

/**
 * Created by liqing on 18/7/3.
 * 审批流程编辑
 * 1.先获取可配置参数 -->没有，则不能编辑
 * 2.可配置，则编辑名称、审批部门、审批人
 * 注：审批流程不可编辑
 */

public class ProducerEditActivity extends BaseActivity {

    private static final int REQUEST_PERSON = 1100;
    @BindView(R.id.edt_producer_name)
    EditText edtProducerName;

    @BindView(R.id.tv_producer_department)
    TextView tvProducerDepart;

    @BindView(R.id.tv_producer_order)
    TextView tvProducerOrder;


    @BindView(R.id.tv_producer_person)
    TextView tvProducerPerson;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.button_back)
    ImageButton backBtn;
    @BindView(R.id.textview_title)
    TextView titleTxt;

    private List<ProducerSettingInfoBean.AvldptsBean> listDeparts = new ArrayList<>();//可配置的审批部门
    private List<ProducerSettingInfoBean.AvlusersBean> listApprover = new ArrayList<>();//可配置人员
    List<Integer> selectDepsId = new ArrayList<>();//已选择的审批部门id
    String[] itemsDeparts = new String[]{""};//可选择的审核部门名称
    String[] itemsApprovers = new String[]{""};//可选择的审核人名称
    private int selectApproverId;//选择的审核人id
    private List<Integer> depts = new ArrayList<>();//现配置的的审批部门id
    private List<Integer> oldDepts = new ArrayList<>();//原配置的的审批部门id
    private int approverId;//原配置的的审批人id
    private int id;//审批流程id
    private StringBuilder sb;
    private StringBuilder sbDeptNames;
    private String oldProducerDepartNames;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_producer_edit);
        initViewEvent();
        getProducerSettingInfo();
        ProducerBean bean = (ProducerBean) getIntent().getSerializableExtra(AppConstant.SERIAL_KEY);
        if (bean != null) {
            edtProducerName.setText(bean.getName());
            id = bean.getId();
            approverId = bean.getChecker();
            sb = new StringBuilder();
            //审批部门集合
            if (bean.getCoverdpts() != null && bean.getCoverdpts().size() > 0) {
                for (int i = 0; i < bean.getCoverdpts().size(); i++) {
                    sb.append(bean.getCoverdpts().get(i).getName());
                    depts.add(bean.getCoverdpts().get(i).getDpt());

                }
                String str = sb.toString();
                tvProducerDepart.setText(str);
                //上次的部门集合名字
                oldProducerDepartNames = str;
            } else {
                tvProducerDepart.setText("");
            }
            tvProducerOrder.setText(bean.getSort() + "");
            tvProducerPerson.setText(bean.getCheckername());
            oldDepts.addAll(depts);
        }
        //stringAppend();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_PERSON) {
            Bundle bundle = data.getExtras();
            MembersBean userBean = (MembersBean) bundle.getSerializable("user");
            tvProducerPerson.setText(userBean.getName());

        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tv_sure:
                checkData();
                break;
            case R.id.tv_producer_department:
                //deparment
                if (listDeparts.size() == 0) {
                    SimpleToast.toastMessage("暂无可配置部门", Toast.LENGTH_SHORT);
                } else {
                    showMultiChoiceDialog();
                }
                break;
            case R.id.tv_producer_order:
                Loger.e("click--tv_producer_level");
                SimpleToast.toastMessage("流程不可更改", Toast.LENGTH_SHORT);

                break;
            case R.id.tv_producer_person:
                Loger.e("click--tv_producer_person");
                if (listApprover.size() == 0) {
                    SimpleToast.toastMessage("暂无可配置人员", Toast.LENGTH_SHORT);
                } else {
                    showSingleChoiceDialog();
                }

                break;
            case R.id.button_back:
                warningDialog(getResources().getString(R.string.cancel_edit));
                break;
            default:
                break;
        }
    }

    private void checkData() {
        String name = edtProducerName.getText().toString();
        String level = tvProducerOrder.getText().toString();

        String depart = tvProducerDepart.getText().toString();
        String person = tvProducerPerson.getText().toString();

        //没有选择部门，就按照原来的
//        if (selectDepsId.size() != 0) {
//            depts.clear();
//            depts.addAll(selectDepsId);
//        }

        if (lastSelectDptIds.size() != 0) {
            depts.clear();
            depts.addAll(lastSelectDptIds);
        }

        if (TextUtils.isEmpty(name)) {
            SimpleToast.toastMessage("审批名称不可为空", Toast.LENGTH_LONG);
            edtProducerName.requestFocus();
            return;
        }


        if (TextUtils.isEmpty(level)) {
            SimpleToast.toastMessage("审批流程不可为空", Toast.LENGTH_LONG);

            return;
        }
        if (TextUtils.isEmpty(depart)) {
            SimpleToast.toastMessage("审批部门不可为空", Toast.LENGTH_LONG);

            return;
        }
        if (depts.size() == 0) {
            SimpleToast.toastMessage("审批部门id不可为空", Toast.LENGTH_LONG);

            return;
        }
        if (TextUtils.isEmpty(person)) {
            SimpleToast.toastMessage("审批人不可为空", Toast.LENGTH_LONG);

            return;
        }


        ProducerUpdateBean bean = new ProducerUpdateBean();
        bean.setName(name);
        bean.setId(id);
        bean.setChecker(approverId);
        bean.setDpts(depts);
        updateProducer(bean);

    }

    @Override
    protected void initViewEvent() {
        tvSure.setOnClickListener(this);
        tvProducerOrder.setOnClickListener(this);
        tvProducerDepart.setOnClickListener(this);
        tvProducerPerson.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        titleTxt.setText(getResources().getString(R.string.edit));
    }

    //网络请求更新编辑的审批流程
    private void updateProducer(ProducerUpdateBean requestBean) {
        Observable<Boolean> observable = new ProducerManageControl().updateProducer(requestBean);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean aBoolean) {
                super.onNext(aBoolean);
                if (aBoolean) {
                    SimpleToast.toastMessage("更新成功", Toast.LENGTH_SHORT);
                    finish();
                }
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_LONG);
                if (t.getMessage().equals("401")) {
                    exit();
                    toActivity(LoginActivity.class);
                }


            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, ProducerEditActivity.this);
    }

    //获取可配置流程的的参数
    private void getProducerSettingInfo() {
        Observable<ProducerSettingInfoBean> observable = new ProducerManageControl().getProducerSettingInfo();
        CommonDialogObserver<ProducerSettingInfoBean> observer = new CommonDialogObserver<ProducerSettingInfoBean>(this) {
            @Override
            public void onNext(ProducerSettingInfoBean bean) {
                super.onNext(bean);
                //  SimpleToast.toastMessage("流程可配置信息获取成功", Toast.LENGTH_SHORT);

                if (bean.getAvldpts() != null && bean.getAvldpts().size() > 0) {
                    //可选择的审核部门
                    //setting department
                    listDeparts.clear();
                    listDeparts.addAll(bean.getAvldpts());
                    //赋值给 department items
                    itemsDeparts = new String[listDeparts.size()];
                    for (int i = 0; i < listDeparts.size(); i++) {
                        itemsDeparts[i] = listDeparts.get(i).getName();
                        Loger.e("depart-" + listDeparts.get(i).getName());
                    }

                }


                if (bean.getAvlusers() != null && bean.getAvlusers().size() > 0) {
                    //可选择的审核人
                    listApprover.clear();
                    listApprover.addAll(bean.getAvlusers());
                    //赋值给 approver items
                    itemsApprovers = new String[listApprover.size()];
                    for (int i = 0; i < listApprover.size(); i++) {
                        itemsApprovers[i] = listApprover.get(i).getName();
                        Loger.e("approver-" + listApprover.get(i).getName());

                    }
                }


            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_LONG);
                    exit();
                    toActivity(LoginActivity.class);
                }


            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, ProducerEditActivity.this);
    }

    List<String> selectNames = new ArrayList<>();
    List<String> selectDptIdStr = new ArrayList<>();

    String selectDepartName;
    String lastSelectDeptNames = "";
    List<Integer> lastSelectDptIds = new ArrayList<>();

    //可配置部门多选框  按了确定，才保存到last，否则不保存，也不更新tv
    Boolean isLast=false;
    private void showMultiChoiceDialog() {

        selectDepsId.clear();
        selectDptIdStr.clear();
        selectDepartName = "";
        selectNames.clear();
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("多选对话框")
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        Loger.e("---oncancleListenr--");
                        isLast=true;

                    }
                })
                .setNegativeButton("取消", null).setPositiveButton("确定", null)

                .setMultiChoiceItems(itemsDeparts, null, new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {


                        if (isChecked) {
                            selectDptIdStr.add(listDeparts.get(which).getDpt() + "");
                            selectNames.add(itemsDeparts[which]);

                        } else {
                            selectDptIdStr.remove(listDeparts.get(which).getDpt() + "");
                            selectNames.remove(itemsDeparts[which]);
                        }

                        selectDepsId.clear();
                        //部门ids
                        if (selectDptIdStr.size() > 0) {

                            for (int i = 0; i < selectDptIdStr.size(); i++) {
                                Loger.e("---IdStr:" + selectDptIdStr.get(i));
                                selectDepsId.add(Integer.valueOf(selectDptIdStr.get(i)));

                            }
                        }

                        for (int i = 0; i < selectDepsId.size(); i++) {
                            Loger.e("---selectDepsId:" + selectDepsId.get(i));

                        }

                        for (int j = 0; j < selectNames.size(); j++) {
                            Loger.e("---selectName:" + selectNames.get(j));

                        }



                    }


                })
                .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Loger.e("----cancel---");
                      //  tvProducerDepart.setText(oldProducerDepartNames);
                      // tvProducerDepart.setText(lastSelectDeptNames);
//                        selectDepsId.clear();
//                        selectDepsId.addAll(oldDepts);
                        isLast=true;
                    }
                })
                .setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Loger.e("----sure---sure----");

                        String name = "";
                        if (selectNames.size() != 0) {
                            for (int j = 0; j < selectNames.size(); j++) {
                                Loger.e("---selectName:" + selectNames.get(j));
                                name = name + selectNames.get(j);
                                Loger.e("--name" + name);
                            }
                        }
                        tvProducerDepart.setText(name);
                        saveData(name);

                    }
                })
                .create();
        dialog.show();

    }


    //保存一下复选框的内容
    private void saveData(String name) {

        lastSelectDptIds.clear();
        lastSelectDptIds.addAll(selectDepsId);
        lastSelectDeptNames=name;

        for (int i = 0; i < lastSelectDptIds.size(); i++) {
            Loger.e("---last--select--dptsid=:" + lastSelectDptIds.get(i));

        }
    }
//
//    //多选可配置部门
//    private void showMultiChoiceDialog() {
//
//        selectDptIdStr.clear();
//        selectDepsId.clear();
//        sbDeptNames = new StringBuilder();
//        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("多选对话框")
//                .setNegativeButton("取消", null).setPositiveButton("确定", null)
//                .setMultiChoiceItems(itemsDeparts, null, new DialogInterface.OnMultiChoiceClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//
//                        if (isChecked) {
//                            selectDptIdStr.add(listDeparts.get(which).getDpt() + "");
//                            selectNames.add(itemsDeparts[which]);
//                            Loger.e("--checked names" + sbDeptNames.toString());
//
//                        } else {
//                            selectDptIdStr.remove(listDeparts.get(which).getDpt() + "");
//                            selectNames.remove(itemsDeparts[which]);
//                        }
//                        Loger.e("multi chocie--dpt" + listDeparts.get(which).getDpt());
//                        sbDeptNames.append(itemsDeparts[which]);
//                        Loger.e("--sb.toString" + sb.toString());
//                        String name = "";
//                        if (selectNames.size() != 0) {
//                            for (int i = 0; i < selectNames.size(); i++) {
//                                name = name + selectNames.get(i);
//                                selectDepsId.add(Integer.valueOf(selectDptIdStr.get(i)));
//                            }
//                        }
//                        tvProducerDepart.setText(name);
//
//
//                    }
//
//                })
//                .create();
//        dialog.show();
//
//
//    }

    //singleChoice审批人选择单选框
    private void showSingleChoiceDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("单选对话框").setIcon(R.drawable.ic_image)
                .setPositiveButton("确定", null)
                .setSingleChoiceItems(itemsApprovers, -1, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Loger.e("choose-whitch--" + which);
                        tvProducerPerson.setText(itemsApprovers[which]);
//                        selectApproverId = listApprover.get(which).getUid();
                        approverId = listApprover.get(which).getUid();
                        Loger.e("--approverId" + approverId);
                        dialog.dismiss();

                    }
                }).create();
        dialog.show();

    }

    protected void warningDialog(String message) {
        new AlertDialog.Builder(ProducerEditActivity.this)
                .setTitle(getResources().getString(R.string.notice))
                .setMessage(message)
                .setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();

                    }
                })
                .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create().show();

    }


    //拦截key back
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            warningDialog("确定退出编辑？数据将不保存");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
